<?php

/*
	this code inspired from:
		http://campstamba.com/2010/12/create-your-own-php-backup-solution-complete-tutorial-with-source-files/
*/

class spSqlBackup
{
	/*
		$tables : has three variants
			1. array of tables
			2. * (will backup all tables)
			3. comma seperated tables
	*/

	private function processTablesParameter( $tables )
	{
		if ( $tables=='*' ) 
		{
			$tables = array();
			$result = mysql_query('SHOW TABLES');
			while ( $row = mysql_fetch_row($result) ) 
			{
				$tables[] = $row[0];
			}
		} 
		else 
		{
			if ( !is_array($tables) ) 
			{
				$tables = explode(',', $tables);
			}
		}

		return $tables;
	}

	public function backup( $tables )
	{
		$return = "";
		
		$tables = $this->processTablesParameter( $tables );
		
		 // cycle through each provided table
		foreach ( $tables as $table ) 
		{
			// we only process tables that exist
			$database = DB_NAME;
			$query = "SHOW TABLES FROM {$database} LIKE '{$table}'";
			$result = mysql_query( $query );
			if ( $result==false || mysql_num_rows($result)==0 )
				continue;
		
			$result = mysql_query('SELECT * FROM '.$table);
			if ( !$result )
			{
				echo "ERROR: mysql_query -> ".$table."</br></br>";
				var_dump( $tables );
				return;
			}
			
			$num_fields = mysql_num_fields($result);
 
			// First part of the output – remove the table
			$return .= 'DROP TABLE ' . $table . ';<|||||||>';
 
			// Second part of the output – create table
			$row2 = mysql_fetch_row(mysql_query('SHOW CREATE TABLE '.$table));
			$return .= "\n\n" . $row2[1] . ";<|||||||>\n\n";
 
			// Third part of the output – insert values into new table
			for ($i = 0; $i < $num_fields; $i++) {
				while($row = mysql_fetch_row($result)) {
					$return.= 'INSERT INTO '.$table.' VALUES(';
					for($j=0; $j<$num_fields; $j++) {
						$row[$j] = addslashes($row[$j]);
						$row[$j] = str_replace("\n","\\n",$row[$j]);
						if (isset($row[$j])) {
							$return .= '"' . $row[$j] . '"';
						} else {
							$return .= '""';
						}
						if ($j<($num_fields-1)) {
							$return.= ',';
						}
					}
					$return.= ");<|||||||>\n";
				}
			}
			$return.="\n\n\n";
		}

		return $return;
	}
	
	public function restore( $text )
	{
	}
}

?>